﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;
using Fluffy.Library.Utils;

namespace Fluffy.Library.Behaviors
{
	public class DragWindowPanelBehavior : Behavior<Panel>
    {
		private bool _restoreIfMove = false;
		private bool _doubleClick = false;
		
        protected override void OnAttached()
        {
            base.OnAttached();

            AssociatedObject.MouseLeftButtonDown += OnMouseDown;
			AssociatedObject.MouseLeftButtonUp += OnMouseUp;
			AssociatedObject.MouseMove += OnMouseMove;
        }
		
		private void OnMouseDown(object sender, MouseButtonEventArgs e)
		{
			Window window = UiUtils.GetParent<Window>(AssociatedObject);

			if (window == null)
				return;

			if (e.ClickCount == 2)
			{
				_doubleClick = true;
				_restoreIfMove = window.WindowState == WindowState.Maximized;
			}
			else if (window.WindowState == WindowState.Maximized)
			{
				_restoreIfMove = true;
			}
			else
			{
				window.DragMove();
			}
		}

		private void OnMouseUp(object sender, MouseButtonEventArgs e)
		{
			_restoreIfMove = false;

			Window window = UiUtils.GetParent<Window>(AssociatedObject);

			if (window == null)
				return;

			if (_doubleClick)
			{
				window.WindowState = window.WindowState == WindowState.Normal ? WindowState.Maximized : WindowState.Normal;
				_doubleClick = false;
			}
		}

		private void OnMouseMove(object sender, MouseEventArgs e)
		{
			_doubleClick = false;

			if (!_restoreIfMove)
				return;

			Window window = UiUtils.GetParent<Window>(AssociatedObject);

			if (window == null)
				return;

			_restoreIfMove = false;

			Point position = e.GetPosition(window);
			Point screenPosition = window.PointToScreen(position);

			double x = position.X / window.ActualWidth * window.RestoreBounds.Width;
			double y = -window.BorderThickness.Top;
			
			window.WindowState = WindowState.Normal;
			window.Left = Math.Min(position.X - x, screenPosition.X - window.BorderThickness.Left - 2);
			window.Top = y;
			window.DragMove();
		}
    }
}
